package com.driving.code.utils;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;

import java.util.ArrayList;
import java.util.Collection;


public class MyModularRealmAuthenticator extends ModularRealmAuthenticator {
    /**
     * 重写认证的方法
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获得全部的Realms
        Collection<Realm> realms = this.getRealms();
        //将 AuthenticationToken 强行转为自定义的 MyUsernamePasswordToken
        MyUsernamePasswordToken myUsernamePasswordToken = (MyUsernamePasswordToken) authenticationToken;
        //获得登录的角色
        String loginRole = myUsernamePasswordToken.getLoginRole();
        //创建一个新的集合用来存储对应角色的 Realm
        Collection<Realm> typeRealms = new ArrayList<>();
        for(Realm realm : realms){
            if (realm.getName().startsWith(loginRole)){
                typeRealms.add(realm);
            }
        }
        //判断如果是单个realm 则执行单个的认证方法，如果是多个，执行多个的认证方法
        if (typeRealms.size() == 1){
            return this.doSingleRealmAuthentication(typeRealms.iterator().next(),myUsernamePasswordToken);
        }else {
            return this.doMultiRealmAuthentication(typeRealms,myUsernamePasswordToken);
        }
    }
}
